package cn.kgc.springcloud.controller;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * @author 课工场
 * @date 2024/7/20
 * @description
 */
@RestController
@RequestMapping("student")
public class StudentController {

    //  spring框架中封装的一个可以发送http请求的对象
    @Resource
    private RestTemplate restTemplate;

    //  ribbon中提供的负载均衡对象
    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("m1")
    public String  method1(){
        //  如何实现发送http请求  scoreController    localhost:8512/score/m1
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject("http://"+randomHost()+"/score/m1", String.class);
        return "studentController service ok >>  scoreController => "+result;
    }


    //  ribbon负载均衡组件的使用
    @GetMapping("m2")
    public String  method2(){
        // 从注册中心中根据服务名拉取通信节点
        // List<ServiceInstance> scoreservice = discoveryClient.getInstances("SCORESERVICE");
        // scoreservice.forEach(instance-> System.out.println(instance.getUri()));
        ServiceInstance scoreservice = loadBalancerClient.choose("SCORESERVICE");
        String result = restTemplate.getForObject(scoreservice.getUri()+"/score/m1", String.class);

        return "studentController service ok >>  scoreController => "+result;
    }


    @GetMapping("m3")
    public String  method3(){
        // 从注册中心中根据服务名拉取通信节点
        String result = restTemplate.getForObject("http://SCORESERVICE/score/m1", String.class);
        return "studentController service ok >>  scoreController => "+result;
    }

    //  随机返回主机节点    1.节点的健康状态无法保证  2. 节点选择的策略单一 随机
    public String randomHost(){
        List<String> list = Arrays.asList("localhost:8512", "localhost:8513", "localhost:8514");
        Random random = new Random();
        int index = random.nextInt(list.size());  // [0,size)
        return list.get(index);
    }

}
